package com.basic.business.img.service.impl;

import com.basic.common.core.domain.AjaxResult;
import com.basic.common.utils.StringUtils;
import com.basic.common.utils.uuid.ULID;
import com.basic.minio.config.MinioConfig;
import com.basic.minio.utils.MinioUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import com.basic.common.core.service.impl.BaseServiceImpl;
import com.basic.business.img.domain.TImagesInfo;
import com.basic.business.img.service.ITImagesInfoService;
import com.basic.business.img.mapper.TImagesInfoMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 业务-素材信息Service业务层处理
 *
 * @author zhaoxy_jn@163.com
 */
@Slf4j
@Service
public class TImagesInfoServiceImpl extends BaseServiceImpl<TImagesInfoMapper,TImagesInfo> implements ITImagesInfoService {

    @Resource
    private TImagesInfoMapper tImagesInfoMapper;

    @Resource
    private MinioConfig minioConfig;

    @Resource
    private MinioUtil minioUtil;

    @Override
    public int updateStatusByIds(String[] ids, String status) {

        for (String id : ids) {
            // 构造图片类
           if (StringUtils.equals(status, "DELETED")) {
               TImagesInfo po = new TImagesInfo();
               po.setId(id);
               po.setFlag("DELETED");
               generateImageVectors(po);
           }
           if (StringUtils.equals(status, "NORMAL")) {
               TImagesInfo po = tImagesInfoMapper.get(id);
               po.setFlag("UPDATE");
               generateImageVectors(po);
           }

        }

        return tImagesInfoMapper.updateStatusByIds(ids, status);
    }

    @Override
    public List<TImagesInfo> getImgInfoByIds(String[] ids) {
        return tImagesInfoMapper.getImgInfoByIds(ids);
    }

    @Override
    public Boolean isExistFile(String imgHash) {
        return tImagesInfoMapper.isExistFile(imgHash) > 0;
    }

    @Override
    public int insert(TImagesInfo po) {
        po.setId(ULID.getId());
        po.setBucketUrl(minioConfig.getEndpoint()+"/"+minioConfig.getBucketName() + "/");

        // 调用 Python 接口生成图片向量
        po.setFlag("ADD");
        generateImageVectors(po);
        return super.insert(po);
    }

    @Override
    public int update(TImagesInfo po) {
        if (StringUtils.isNotBlank(po.getFlag())) {
            // 调用Python接口更新图片向量
            generateImageVectors(po);
        }

        return super.update(po);
    }

    @Transactional
    @Override
    public int deleteByIds(Object[] ids) {
        // 将 Object 数组转换为 String 数组
        String[] idStrings = Arrays.stream(ids).map(Object::toString).toArray(String[]::new);

        // 根据ids查询文件，获取文件的路径
        List<TImagesInfo> imgInfos = tImagesInfoMapper.getImgInfoByIds(idStrings);
        imgInfos.forEach(imgInfo -> {
            minioUtil.deleteFile(imgInfo.getImgSourcePath());
            minioUtil.deleteFile(imgInfo.getImgJpgPath());
            minioUtil.deleteFile(imgInfo.getImgPngPath());
        });
        for (String id : idStrings) {
            TImagesInfo po = new TImagesInfo();
            po.setId(id);
            po.setFlag("DELETED");
            generateImageVectors(po);
        }
        return super.deleteByIds(ids);
    }

    /**
     * 调用 Python 接口生成图片向量
     */
    private void generateImageVectors(TImagesInfo tImagesInfo) {
        try {
            new Thread(() -> {
                // 2. 设置请求头（Content-Type: application/json）
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);

                // 3. 发送请求
                RestTemplate restTemplate = new RestTemplate();
                String response = restTemplate.postForObject(
                        "http://127.0.0.1:8998/generate_image_vectors",
                        new HttpEntity<>(tImagesInfo, headers),
                        String.class
                );
            }).start();
        } catch (Exception e) {
            log.error("调用Python计算图片向量失败：", e);
        }
    }

    @Override
    public AjaxResult searchImage(MultipartFile file) {

        try {
            // 创建一个MultiValueMap来存储文件和其他参数
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            // 使用 InputStreamResource 进行流式传输
            body.add("file", new ByteArrayResource(file.getBytes()) {
                @Override
                public String getFilename() {
                    return file.getOriginalFilename(); // 设置文件名
                }
            });

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            // 创建HttpEntity
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

            // 发送请求
            RestTemplate restTemplate = new RestTemplate();
            String response = restTemplate.postForObject(
                    "http://127.0.0.1:8998/find_image_vectors",
                    requestEntity,
                    String.class
            );

            return AjaxResult.success(response);
        } catch (Exception e) {
            log.error("调用Python搜索图片失败：", e);
            return AjaxResult.error("调用TBIR失败");
        }
    }

    @Override
    public Map<String, Integer> getVectorsCount() {
        return tImagesInfoMapper.getVectorsCount();
    }
}
